package com.zzxz.practicaltrainingsys.service.impl;

import com.zzxz.practicaltrainingsys.entity.Circle;
import com.zzxz.practicaltrainingsys.entity.Circlecomment;
import com.zzxz.practicaltrainingsys.entity.Circlefile;
import com.zzxz.practicaltrainingsys.mapper.CircleMapper;
import com.zzxz.practicaltrainingsys.service.CircleService;
import com.zzxz.practicaltrainingsys.util.circleFileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;

@Service
public class CircleServiceImpl implements CircleService {
    private static final Logger logger = LoggerFactory.getLogger(CircleServiceImpl.class);

    @Autowired
    private CircleMapper circleMapper;

    @Override
    public List<Circle> getCircleList(String sort) {
        List<Circle> circles = circleMapper.getCircleList(sort);
        circles.forEach(circle -> {
            int commentCount = circleMapper.getCommentsByCircleId(circle.getCircle_id()).size();
            circle.setCommentCount(commentCount);
            List<Circlefile> files = circleMapper.getFilesByCircleId(circle.getCircle_id());
            circle.setFiles(files);
        });
        return circles;
    }

    @Override
    public Circle getCircleDetail(Integer circleId) {
        Circle circle = circleMapper.getCircleById(circleId);
        if (circle != null) {
            int commentCount = circleMapper.getCommentsByCircleId(circleId).size();
            circle.setCommentCount(commentCount);
            List<Circlefile> files = circleMapper.getFilesByCircleId(circleId);
            circle.setFiles(files);
        }
        return circle;
    }

    @Override
    public Integer createCircle(Circle circle, List<MultipartFile> files) {
        circleMapper.insertCircle(circle);
        Integer circleId = circle.getCircle_id();

        if (files == null || files.isEmpty()) {
            return circleId;
        }

        for (MultipartFile file : files) {
            try {
                String originalFilename = file.getOriginalFilename();
                String fileType = file.getContentType();

                if (fileType == null || fileType.isEmpty()) {
                    fileType = getFileTypeFromName(originalFilename);
                }

                String fileName = UUID.randomUUID().toString() + getFileExtension(originalFilename);

                String filePath, fileUrlPrefix;
                if (fileType.startsWith("image/")) {
                    filePath = circleFileUtil.getUpLoadFilePath();
                    fileUrlPrefix = "/images/upload/circle/";
                } else {
                    filePath = circleFileUtil.getAttachmentFilePath();
                    fileUrlPrefix = "/attachments/upload/circle/";
                }

                File targetDir = new File(filePath);
                if (!targetDir.exists()) {
                    targetDir.mkdirs();
                }

                circleFileUtil.uploadFile(file.getBytes(), filePath, fileName);

                Circlefile circlefile = new Circlefile();
                circlefile.setCircle_id(circleId);
                circlefile.setFile_type(fileType != null ? fileType : "application/octet-stream");
                circlefile.setFile_url(fileUrlPrefix + fileName);
                circlefile.setFile_size(file.getSize());
                circlefile.setFile_name(originalFilename);
                circleMapper.insertCirclefile(circlefile);

                logger.info("文件上传成功: {}, 类型: {}, 保存路径: {}", originalFilename, fileType, filePath);

            } catch (Exception e) {
                logger.error("文件上传失败: {}", file.getOriginalFilename(), e);
                throw new RuntimeException("文件上传失败: " + file.getOriginalFilename(), e);
            }
        }
        return circleId;
    }

    private String getFileExtension(String filename) {
        if (filename == null || filename.lastIndexOf(".") == -1) {
            return "";
        }
        return filename.substring(filename.lastIndexOf("."));
    }

    private String getFileTypeFromName(String filename) {
        if (filename == null) {
            return "application/octet-stream";
        }

        String extension = getFileExtension(filename).toLowerCase();
        switch (extension) {
            case ".jpg":
            case ".jpeg":
                return "image/jpeg";
            case ".png":
                return "image/png";
            case ".gif":
                return "image/gif";
            case ".pdf":
                return "application/pdf";
            case ".doc":
            case ".docx":
                return "application/msword";
            case ".xls":
            case ".xlsx":
                return "application/vnd.ms-excel";
            case ".ppt":
            case ".pptx":
                return "application/vnd.ms-powerpoint";
            case ".zip":
                return "application/zip";
            case ".rar":
                return "application/x-rar-compressed";
            default:
                return "application/octet-stream";
        }
    }

    @Override
    public Integer addComment(Circlecomment comment) {
        circleMapper.insertComment(comment);
        return comment.getComment_id();
    }

    @Override
    public List<Circlecomment> getCommentsWithReply(Integer circleId) {
        List<Circlecomment> comments = circleMapper.getCommentsByCircleId(circleId);
        Map<Integer, Circlecomment> commentMap = new HashMap<>();
        List<Circlecomment> rootComments = new ArrayList<>();

        // 初始化所有评论的 children 列表
        for (Circlecomment comment : comments) {
            comment.setChildren(new ArrayList<>());
            commentMap.put(comment.getComment_id(), comment);

            // 统一评论人姓名和头像字段
            comment.setStudent_name(comment.getCommenter_name());
            comment.setStudent_image(comment.getCommenter_image());
        }

        // 扁平化处理：将所有回复提升到根节点下
        List<Circlecomment> flattenedComments = new ArrayList<>();
        for (Circlecomment comment : comments) {
            // 如果是顶级评论，直接加入
            if (comment.getRecomment_id() == null) {
                flattenedComments.add(comment);
            }
            // 如果是回复评论，提升为顶级评论（但标记为回复）
            else {
                // 查找被回复的评论
                Circlecomment parent = commentMap.get(comment.getRecomment_id());
                if (parent != null) {
                    // 更新回复对象信息
                    comment.setReply_to(parent.getCommenter_name());
                    // 设置新的回复ID为顶级评论ID
                    comment.setRecomment_id(parent.getRecomment_id() != null ?
                            parent.getRecomment_id() :
                            parent.getComment_id());
                }
                flattenedComments.add(comment);
            }
        }

        // 构建评论树（只有两级）
        for (Circlecomment comment : flattenedComments) {
            if (comment.getRecomment_id() != null) {
                Circlecomment parent = commentMap.get(comment.getRecomment_id());
                if (parent != null) {
                    parent.getChildren().add(comment);
                }
            } else {
                rootComments.add(comment);
            }
        }

        return rootComments;
    }

    //点赞（根据circle_id更新circle_good）
    @Override
    public int likeCircle(String circle_good, Integer circle_id) {
        return circleMapper.likeCircle(circle_good, circle_id);
    }

    @Override
    public List<Circle> getCircleByRoleAndId(Integer circlestu_id, String circle_role, String sort) {
        List<Circle> circles = circleMapper.getCircleByRoleAndId(circlestu_id, circle_role, sort);
        circles.forEach(circle -> {
            int commentCount = circleMapper.getCommentsByCircleId(circle.getCircle_id()).size();
            circle.setCommentCount(commentCount);
            List<Circlefile> files = circleMapper.getFilesByCircleId(circle.getCircle_id());
            circle.setFiles(files);
        });
        return circles;
    }

    @Override
    public void updateCircle(Circle circle, List<MultipartFile> files) {
        // 1. 更新帖子基本信息
        circleMapper.updateCircle(circle);

        // 2. 处理删除的文件
        if (circle.getDeleted_files() != null) {
            for (Integer fileId : circle.getDeleted_files()) {
                try {
                    Circlefile file = circleMapper.getFileById(fileId);
                    if (file != null) {
                        deletePhysicalFile(file);
                        circleMapper.deleteFile(fileId);
                        logger.info("删除文件成功: {}", fileId);
                    }
                } catch (Exception e) {
                    logger.error("删除文件失败: {}", fileId, e);
                    // 不中断整个流程，继续处理其他文件
                }
            }
        }

        // 3. 处理新上传的文件
        if (files != null && !files.isEmpty()) {
            for (MultipartFile file : files) {
                try {
                    String originalFilename = file.getOriginalFilename();
                    String fileType = file.getContentType();
                    long fileSize = file.getSize();

                    if (fileType == null || fileType.isEmpty()) {
                        fileType = getFileTypeFromName(originalFilename);
                    }

                    // 检查文件大小
                    if (fileType.startsWith("image/") && fileSize > 100 * 1024 * 1024) {
                        throw new RuntimeException("图片大小超过100MB限制");
                    } else if (fileSize > 200 * 1024 * 1024) {
                        throw new RuntimeException("附件大小超过200MB限制");
                    }

                    String fileName = UUID.randomUUID() + getFileExtension(originalFilename);
                    String filePath, fileUrlPrefix;

                    if (fileType.startsWith("image/")) {
                        filePath = circleFileUtil.getUpLoadFilePath();
                        fileUrlPrefix = "/images/upload/circle/";
                    } else {
                        filePath = circleFileUtil.getAttachmentFilePath();
                        fileUrlPrefix = "/attachments/upload/circle/";
                    }

                    // 确保目录存在
                    File targetDir = new File(filePath);
                    if (!targetDir.exists() && !targetDir.mkdirs()) {
                        throw new RuntimeException("无法创建目录: " + filePath);
                    }

                    // 保存文件
                    circleFileUtil.uploadFile(file.getBytes(), filePath, fileName);

                    // 创建文件记录
                    Circlefile circlefile = new Circlefile();
                    circlefile.setCircle_id(circle.getCircle_id());
                    circlefile.setFile_type(fileType);
                    circlefile.setFile_url(fileUrlPrefix + fileName);
                    circlefile.setFile_size(fileSize);
                    circlefile.setFile_name(originalFilename);
                    circleMapper.insertCirclefile(circlefile);

                    logger.info("文件上传成功: {}, 类型: {}, 大小: {}字节",
                            originalFilename, fileType, fileSize);

                } catch (Exception e) {
                    logger.error("文件上传失败: {}", file.getOriginalFilename(), e);
                    throw new RuntimeException("文件上传失败: " + file.getOriginalFilename() +
                            " - " + e.getMessage());
                }
            }
        }
    }

    private void deletePhysicalFile(Circlefile file) {
        try {
            String filePath;
            if (file.getFile_type().startsWith("image/")) {
                filePath = circleFileUtil.getUpLoadFilePath();
            } else {
                filePath = circleFileUtil.getAttachmentFilePath();
            }

            String fileName = file.getFile_url().substring(file.getFile_url().lastIndexOf("/") + 1);
            File physicalFile = new File(filePath + File.separator + fileName);

            if (physicalFile.exists()) {
                if (physicalFile.delete()) {
                    logger.info("物理文件删除成功: {}", physicalFile.getAbsolutePath());
                } else {
                    logger.warn("物理文件删除失败: {}", physicalFile.getAbsolutePath());
                }
            } else {
                logger.warn("物理文件不存在: {}", physicalFile.getAbsolutePath());
            }
        } catch (Exception e) {
            logger.error("删除物理文件失败", e);
        }
    }

    @Override
    public void deleteCircle(Integer circleId) {
        // 1. 删除关联文件（数据库记录和物理文件）
        List<Circlefile> files = circleMapper.getFilesByCircleId(circleId);
        for (Circlefile file : files) {
            deletePhysicalFile(file);
        }

        // 2. 删除数据库记录
        circleMapper.deleteCircleFiles(circleId);  // 删除文件记录
        circleMapper.deleteComments(circleId);     // 删除评论
        circleMapper.deleteCircle(circleId);       // 删除帖子
    }

    @Override
    public List<Map<String, String>> getLikedUsers(String userIds) {
        if (userIds == null || userIds.isEmpty()) {
            return new ArrayList<>();
        }
        return circleMapper.getLikedUsers(userIds);
    }

    @Override
    public void deleteComment(Integer commentId) {
        circleMapper.deleteCommentRecursive(commentId);
    }
}